package com.gzhryc.shared_device.cdcz.code;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.cdcz.core.protocol.v1.V1_CDCZConstants;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocket;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZOrder;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketService;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderService;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.cdcz.core.models.CDCZChargeCommand;
import com.gzhryc.shared_device.cdcz.core.models.CDCZExecuteResult;

public class CDCZWorkThread implements Runnable{

    static Logger log = Logger.getLogger(CDCZWorkThread.class);

    final String jdbcKey;
    final CDCZOrder deviceOrder;
    final ICDCZNetworkService networkService;
    final OperateInfo operateInfo;


    public CDCZWorkThread(String jdbcKey, CDCZOrder deviceOrder, ICDCZNetworkService networkService, OperateInfo operateInfo){
        this.jdbcKey = jdbcKey;
        this.deviceOrder = deviceOrder;
        this.networkService = networkService;
        this.operateInfo = operateInfo;
    }

    @Override
    public void run() {
        log.info("充电插座工作线程，执行订单：{{0}}，数据库Key：{{1}}", deviceOrder.getTradeNo(), jdbcKey);
        try {
            MultiDBTools.setJdbcKey(jdbcKey);
            ChargeSocket chargeSocket = ChargeSocketService.self().getByDeviceSn(deviceOrder.getChargeSocketSn());
            if (chargeSocket != null) {
                if (networkService != null) {
                    //设置工作缓存，用于IOT回调时根据消息ID获取订单信息
                    String msgId = V1_CDCZConstants.getMessageId();
                    CDCZWorkCacheManager.DeviceWorkInfo deviceWorkInfo = new CDCZWorkCacheManager.DeviceWorkInfo();
                    deviceWorkInfo.setDeviceSn(deviceOrder.getChargeSocketSn());
                    deviceWorkInfo.setSlotNum(deviceOrder.getSlotNum());
                    deviceWorkInfo.setTradeNo(deviceOrder.getTradeNo());
                    if (!CDCZWorkCacheManager.self().setData(msgId, deviceWorkInfo)) {
                        log.error("充电插座工作线程，缓存设备工作信息失败，msgId = {{0}}，信息：{{1:json}}", msgId, deviceWorkInfo);
                    }
                    if (CDCZOrderService.self(deviceOrder.getCreateDate()).waitStartToOpening(deviceOrder.getTradeNo(), deviceOrder.getChargeSocketSn(), deviceOrder.getSlotNum())) {
                        boolean flag = true;
                        try {
                            CDCZChargeCommand command = new CDCZChargeCommand();
                            command.setMessageId(msgId);
                            command.setDeviceSn(deviceOrder.getChargeSocketSn());
                            command.setSlotNum(deviceOrder.getSlotNum());
                            command.setTradeNo(deviceOrder.getTradeNo());
                            command.setCostMode(deviceOrder.getCostMode());
                            command.setChargeElectricity(deviceOrder.getMaxUseChargeElectricity());
                            command.setChargeTimes(deviceOrder.getMaxUseTimes());

                            CDCZExecuteResult executeResult = networkService.charge(command);
                            if (executeResult != null) {
                                if (CDCZExecuteResult.SUCCESS.equals(executeResult.getCode())) {
                                    flag = false;
                                } else if (StringTools.isNotBlank(executeResult.getMsg())) {
                                    log.error("发送命令失败，返回错误：{{0}}，订单：{{1}}", executeResult.getMsg(), deviceOrder.getTradeNo());
                                } else {
                                    log.error("发送命令失败，订单：{{0}}", deviceOrder.getTradeNo());
                                }
                            } else {
                                log.error("充电插座网络服务无响应，订单：{{0}}", deviceOrder.getTradeNo());
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        } finally {
                            if (flag) {
                                log.error("充电插座订单{{0}}开启失败，启动自动退款功能", deviceOrder.getTradeNo());
                                CDCZOrderService.self(deviceOrder.getCreateDate()).openingFail(deviceOrder, operateInfo);
                            }
                        }
                    } else {
                        log.error("充电插座订单{{0}}从等待开始->开启中修改失败", deviceOrder.getTradeNo());
                    }
                } else {
                    log.error("未找到充电插座设备网络服务，IOT节点：{{0}}，设备序列号：{{1}}，订单号：{{2}}", chargeSocket.getIotNodeId()
                            , chargeSocket.getDeviceSn(), deviceOrder.getTradeNo());
                }
            } else {
                log.error("未找到充电插座设备{{0}}，订单号：{{1}}", deviceOrder.getChargeSocketSn(), deviceOrder.getTradeNo());
            }
        } finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
    }
}
